package com.mj.controller;
  
import java.util.Map;  
import java.util.concurrent.ConcurrentHashMap;  
  
import javax.websocket.*;  
import javax.websocket.server.PathParam;  
import javax.websocket.server.ServerEndpoint;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
/** 
 * 使用webSocket实现微信完成订单的推送
 */  
@ServerEndpoint("/wxPay/{outTradeNo}")  
public class WebsocketController {  
    private static final Logger logger = LoggerFactory.getLogger(WebsocketController.class);  
  
    /**
     * 用来存放进入的链接session
     */
    public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>();  
  
    /** 
     * 打开连接时触发 
     * @param outTradeNo 
     * @param session 
     */  
    @OnOpen  
    public void onOpen(@PathParam("outTradeNo") String outTradeNo, Session session){  
        logger.info("Websocket Start Connecting:" + outTradeNo);  
        //缓存链接信息
        clients.put(outTradeNo, session);  
    }  
  
    /** 
     * 收到客户端消息时触发 
     * @param outTradeNo 
     * @param message 
     * @return 
     */  
    @OnMessage  
    public String onMessage(@PathParam("outTradeNo") String outTradeNo, String message) {  
        return "Got your message ("+ message +").Thanks !";  
    }  
  
    /** 
     * 异常时触发 
     * @param outTradeNo 
     * @param throwable 
     */  
    @OnError  
    public void onError(@PathParam("outTradeNo") String outTradeNo, Throwable throwable) {  
        logger.info("Websocket Connection Exception:" + outTradeNo);  
        //链接异常时候删除连接
        clients.remove(outTradeNo);  
    }  
  
    /** 
     * 关闭连接时触发 
     * @param outTradeNo 
     */  
    @OnClose  
    public void onClose(@PathParam("outTradeNo") String outTradeNo) {  
        logger.info("Websocket Close Connection:" + outTradeNo);  
        //链接异常时候删除连接
        clients.remove(outTradeNo);  
    }  
  
  
    /** 
     * 将数据传回客户端 
     * 异步的方式 
     * @param outTradeNo 
     * @param message 
     */  
    public static void broadcast(String outTradeNo, String message) {  
        if (clients.containsKey(outTradeNo)) {  
            clients.get(outTradeNo).getAsyncRemote().sendText(message);  
        } else {  
            throw new NullPointerException("[" + outTradeNo +"]Connection does not exist");  
        }  
    }  
  
}  